package de.hsos.bose.skillshare.model.core.combobox;

import java.util.List;
import java.util.Vector;

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

import de.hsos.bose.skillshare.model.core.DataAccess;
import de.hsos.bose.skillshare.model.objects.Mitarbeiter;
import de.hsos.bose.skillshare.model.objects.SkillRating;

public class AssignmentComboBoxModel extends AbstractListModel implements
		ComboBoxModel {

	private static final long serialVersionUID = 1L;

	protected Vector<Mitarbeiter> dataVector;
	protected Mitarbeiter selectedObject = null;
	
	public AssignmentComboBoxModel() {
		this.dataVector = new Vector<Mitarbeiter>();
	}
	
	public void loadEmpoyees(int adminId, int rollId) {
		while(dataVector.size() > 0){
			dataVector.remove(0);
			fireIntervalRemoved(this, 0, 0);
		}
		selectedObject = null;
		DataAccess da = new DataAccess();
		List<Mitarbeiter> mitaList = da.getPossibleAssignMitarbeiter(adminId, rollId);

		for (Mitarbeiter mita : mitaList) {
			dataVector.add(mita);
			fireIntervalAdded(this, dataVector.size(), dataVector.size());
		}
	}
	
	public void setSelectedItem(Object item) {
		System.out.println("item: " + item);
		int index = -1;
		if (item instanceof SkillRating) {
			setSelectedItem(((Mitarbeiter) item).getId());
		} else if (item instanceof String) {
			index = -1;
			for (int i = 0; i < this.dataVector.size(); i++) {
				if (((Mitarbeiter) this.dataVector.elementAt(i))
						.toName().equals(item)) {
					System.out.println("index: " + i);
					index = i;
					selectedObject = this.dataVector.elementAt(i);
					break;
				}
			}
			if (index < 0) {
				selectedObject = null;
			}
		} else {
			index = -1;
			for (int i = 0; i < this.dataVector.size(); i++) {
				if (((Mitarbeiter) this.dataVector.elementAt(i)).getId() == (Integer) item) {
					index = i;
					selectedObject = this.dataVector.elementAt(i);
					break;
				}
			}
			if (index < 0) {
				selectedObject = null;
			}
		}
		fireContentsChanged(this, index, index);
	}
	
	@Override
	public Object getElementAt(int i) {
		System.out.println("i: " + i);
		if (getSize() > 0) {
			return dataVector.elementAt(i).toName();
		}
		return null;
	}

	@Override
	public int getSize() {
		return dataVector.size();
	}

	@Override
	public Object getSelectedItem() {
		if (selectedObject == null || getSize() == 0) {
			
			return null;
		}
		return selectedObject.toName();
	}
	
	public Mitarbeiter getItem() {
		if (selectedObject == null) {
			return null;
		}
		return selectedObject;
	}

	
}
